//
//  MapViewController.mm
//  iLo
//
//  Created by Huahang Liu on 10/9/09.
//  Copyright 2009 University of Southern California. All rights reserved.
//

#import "MapViewController.h"
#import "iDashanAppDelegate.h"

@implementation MapViewController

@synthesize mapView;
@synthesize locationManager;
@synthesize friendsDb;

- (void)refreshCurrentLocation:(id)sender {
    NSLog(@"refreshCurrentLocation");
    [locationManager startUpdatingLocation];
}

/*
// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    // Find current location and set the map position and size
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    self.locationManager.delegate = self;
    // Refressh location button
    UIBarButtonItem* refreshBarButton = [[[UIBarButtonItem alloc] 
                                          initWithTitle:@"Refresh"
                                          style:UIBarButtonItemStyleBordered
                                          target:self
                                          action:@selector(refreshCurrentLocation:)] autorelease];
    self.navigationItem.rightBarButtonItem = refreshBarButton;
    
    [super viewDidLoad];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    [mapView removeFromSuperview];  mapView = nil;
    [locationManager release];      locationManager = nil;
    
}


- (void)dealloc {
    [mapView release];
    [friendsDb release];
    [super dealloc];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    [locationManager stopUpdatingLocation];

    NSLog(@"Done updating.");
    MKCoordinateRegion region;
    region.center.latitude  = newLocation.coordinate.latitude;
    region.center.longitude = newLocation.coordinate.longitude;
    region.span.latitudeDelta  = 0.010f;
    region.span.longitudeDelta = 0.010f;
    [mapView setRegion:region animated:YES];
    [mapView addAnnotation:(id<MKAnnotation>)newLocation];
    
    // Refresh location
    iDashanAppDelegate* appDelegate = (iDashanAppDelegate*)[[UIApplication sharedApplication] delegate];
    NSString* postLocationBase = [NSString stringWithFormat:@"http://dashan-net.appspot.com/postlocation"];
    NSString* usernameStr  = appDelegate.username;
    NSString* latitudeStr  = [NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];
    NSString* longitudeStr = [NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
    NSString* accuracyStr  = [NSString stringWithFormat:@"%f", newLocation.horizontalAccuracy];

    NSString* urlStr = [NSString stringWithFormat:@"%@?username=%@&latitude=%@&longitude=%@&accuracy=%@", 
                         postLocationBase, usernameStr, latitudeStr, longitudeStr, accuracyStr];
    NSURL* theURL = [NSURL URLWithString:urlStr];
    
    NSMutableURLRequest* theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
    [theRequest setHTTPMethod:@"POST"];    
    NSURLResponse* theResponse = NULL;
    NSError* theError = NULL;
    NSData* theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
    NSString* theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"%@", theResponseString);
    
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {

}



@end
